package com.eip.zd.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eip.zd.entity.Cust;
import com.eip.zd.exception.CustomException;
import com.eip.zd.mapper.CustMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CustService {
    @Resource
    private CustMapper custMapper;

    public List<Cust> getCustList(String keyword) {
        QueryWrapper<Cust> wrapper = new QueryWrapper<>();
        wrapper.like(keyword != null, "name", keyword).or().eq(keyword != null, "cust_id", keyword);
        return custMapper.selectList(wrapper);
    }

    public Cust getCustById(String custId) {
        QueryWrapper<Cust> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_id", custId);
        wrapper.eq("deleted", 0);
        return custMapper.selectOne(wrapper);
    }

    public void add(Cust cust) {
        if (StrUtil.hasEmpty(cust.getCustId())) {
            throw new CustomException(500, "客户编号不能为空");
        }
        if (getCustById(cust.getCustId()) != null) {
            throw new CustomException(500, "该客户已存在");
        }
        custMapper.insert(cust);
    }

    public void update(Cust cust) {
        if (StrUtil.hasEmpty(cust.getCustId())) {
            throw new CustomException(500, "客户编号不能为空");
        }
        custMapper.updateById(cust);
    }

    public void remove(Long id) {
        Cust cust = custMapper.selectById(id);
        cust.setIfUse(2);
        custMapper.updateById(cust);
        custMapper.deleteById(id);
    }

    public void ifUse(Long id) {
        Cust cust = custMapper.selectById(id);
        if (cust.getIfUse() == 1) {
            cust.setIfUse(2);
        } else {
            cust.setIfUse(1);
        }
        custMapper.updateById(cust);
    }

    public List<Cust> getTenCust(String keyword) {
        QueryWrapper<Cust> wrapper = new QueryWrapper<>();
        wrapper.eq("if_use", 1).and(qw -> {
            qw.like("name", keyword).or().eq("cust_id", keyword);
        });
        List<Cust> custList = custMapper.selectList(wrapper);
        if (custList.size() > 10) {
            return custList.subList(0, 10);
        }
        return custList;
    }

    public Cust getCustByCustId(String custId) {
        QueryWrapper<Cust> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_id", custId);
        return custMapper.selectOne(wrapper);
    }
}
